require('date-utils');
var settings = require('../config');
var models = require("../models"),
    Message = models.Message,
    User = models.User,
    WCSession = models.WCSession,
    PayOff = models.PayOff,
    PubChatPay = models.PubChatPay,
    SignIn = models.SignIn;
var wechat_util = require('./wechatutil');
var _ = require('underscore');
var debug = require('debug')('consultant:utils');
var async = require('async');
var tool = function () {

};
/**
 *统一处理从微信平台上接收到的用户发送的消息
 */
tool.prototype.processMessage = function (message) {
    debug('get message:', message);
    //判断消息来源获取发送者openid
    var fromOpneid = message.FromUserName;
    var userDao = new User();
    var sessionDao = new WCSession();
    //根据openid判断用户是否已经创建会话且会话未结束（此用户可以是自信用户和咨询师）
    sessionDao.findSessionByOpenId({
        status: 1
    }, fromOpneid, function (err, sessions) {
        var session = sessions[0]; //如过一个咨询用户创建了多于1个的session取第一个就可以因为抢单的时候会将所有属于这个咨询用户发起的会话的receive_openid改为抢单者的openid
        if (sessions.length > 0) { //如果已经创建会话根据用户表中的会话直接将消息发送给接收方
            userDao.findUserByOpenid(fromOpneid, function (err, user) { //根据openid查找用户信息
                var nickname = user.nickname;
                var reveiceer; //消息的接收者
                if (err || !user) {
                    debug("find no user or error", err);
                } else {
                    checkSessionTimeOut(session.send_openid, session, function (flag) { //检查会话是否超时
                        if (flag) { //如果会话已经超时
                            debug("the session is timeout!", flag);
                            //重新判断询问次数，之后将消息发送给5名咨询师
                            userAsk(user, message, function (err) {
                                if (err) {
                                    debug("userAsk fail!!", err);
                                }
                            })
//                            }
                        } else { //会话未超时
                            if (session.receive_openid == fromOpneid) {
                                reveiceer = session.send_openid;
                            } else { //如果是咨询用户，则将消息发送给咨询师
                                reveiceer = session.receive_openid;
                            }
                            //发送消息
                            new wechat_util().getAPI(function (api) {
                                var msg = {
                                    "nickname": nickname,
                                    "message": message,
                                    "sendopenid": reveiceer
                                }
                                sendMessage(api, msg, message.MsgType);
                            })
                        }
                    });
                    // //消息存储
                    new tool().saveMsg(message, function (err) {
                        debug("add new Message", err);
                    })
                }
            });

        } else { //如果没有创建会话，根据openid判断用户来源是咨询师还是咨询用户
            userDao.findUserByOpenid(fromOpneid, function (err, user) {
                if (err || !user) {
                    debug("find no user or error", err);
                } else {
                    var nickname = user.nickname;
                    //用户发问，创建会话
                    userAsk(user, message, function (err) {
                        if (err) {
                            debug("userAsk fail!!", err);
                        }
                    })
                }
            })
        }
    });
};
/**
 * 处理用户评价
 * @param message
 */
tool.prototype.processComment = function (message, callback) {
    var sessionDao = new WCSession();
    //判断系统接收到的消息是否为用户评价的消息
    var fromOpneid = message.FromUserName;
    var isnumber = parseInt(message.Content);
    var regnumber = /^[1-3]{1}$/;
    if (_.isNaN(isnumber)) {//判断用户发送的消息是否为数据
        //如果不是数字执行处理消息操作
        callback(true);
    } else if (regnumber.test(isnumber)) {//如果发送的是数字而且还是0、1或2则执行评价操作
        sessionDao.findSessionByOpenId({
            status: 2,
            comment: 0,//评分
            receive_openid: {
                $ne: null
            }
        }, fromOpneid, function (err, sessions) {
            if (sessions.length > 0) {//如果客户目前有两个未进行评价的对话,系统将评价的结果给最近一个对话
                if (sessions.length > 1){//如果大于1条数据，把除最近会话之外的comment改为1
                    for(var i=1;i<sessions.length;i++){
                        sessionDao.updateSessionCommon({
                            "_id": sessions[i]._id
                        }, {
                            "comment": 1
                        }, false, function (err) {
                            if(err){
                                debug("updateSessionCommon fail[i]");
                            }

                        })
                    }
                }

                sessionDao.updateSessionCommon({//系统将评价的结果给最近一个对话
                    "_id": sessions[0]._id
                }, {
                    "comment": isnumber
                }, false, function (err) {
                    if (err) {
                        debug("updateSessionCommon fail");
                    } else {
                        //发送评价消息
                        new wechat_util().getAPI(function (api) {
                            var sendmsg = "系统消息：感谢您对我们服务的支持，谢谢您的使用!!";
                            var msg = {
                                "sendtextmsg": sendmsg,
                                "sendopenid": fromOpneid
                            }
                            sendMessage(api, msg, "text");
                        })
                        callback(false);
                    }
                })
            } else {
                //执行处理消息操作
                callback(true);
            }
        })
    } else {
        //执行处理消息操作
        callback(true);
    }
}
/**
 *判断用户会话是否已经过时,如果已经超时将用户会话的状态更新为结束。
 */
function checkSessionTimeOut(sendopenid, session, callback) {
    var checkdate;
    var timeoutdate;
    if (session.relet_date) {
        checkdate = session.relet_date;
    } else {
        checkdate = session.build_date;
    }
    var curdate = new Date();
    var diftime = (curdate - checkdate) / 1000;
    if (diftime > settings.wc_session_timeout) {
        //如果会话已经超时，更新会话状态
        new WCSession().updateSessionBySendOpneId2(sendopenid, function (err) {
            if (err) {
                debug("session timeout update fail", err);
            } else {
                //已经超时
                callback(true);
            }
        })
    } else {
        callback(false);
    }
}
/**
 *存储消息
 */
tool.prototype.saveMsg = function (message, callback) {
    var sessionDao = new WCSession();//查询sessionid

    sessionDao.findSessionIdByStatus(message.FromUserName,1,function(err,wcsesson){
        var sessionid = '';
        //var receiveid = '';
        if(wcsesson.length>0){
            sessionid = wcsesson[0]._id;
            //receiveid = wcsesson[0].receive_openid
        }


        var msg = new Message({
            send_openid: message.FromUserName,
            receive_openid: message.ToUserName,//公众账号ID
            //receive_openid: receiveid,
            msgid: message.MsgId,
            msgtype: message.MsgType,
            date: message.CreateTime,
            wcsessionid: sessionid,
            messageinfo: message
        });
        if (message.MsgType == "text") {
            msg.sendcontent = message.Content;
            msg.saveMessage(msg, function (err) {
                if (err) debug("save message fail", err);
            });
        } else if (message.MsgType == "image") {
            //getImage(message);
            var wechatutil = new wechat_util();
            wechatutil.getAPI(function(api){
                api.getMedia(message.MediaId,function(err,result,res){
                    /*console.log(result);*/
                    msg.sendcontent = result.toString('base64');
                    msg.saveMessage(msg, function (err) {
                        if (err) debug("save message fail", err);
                    });

                })
            });

        } else if (message.MsgType == "voice") {
            msg.sendcontent = message.MediaId;
            msg.saveMessage(msg, function (err) {
                if (err) debug("save message fail", err);
            });
        } else if (message.MsgType == "video") {
            msg.sendcontent = message.MediaId + ";" + message.ThumbMediaId;
            msg.saveMessage(msg, function (err) {
                if (err) debug("save message fail", err);
            });
        }

    });


}

/**
 * 热门话题回复
 */
tool.prototype.sentImgText = function(message,cb){
    var openid = message.FromUserName;
    var searchResult = new Array();
    var session = new WCSession();
    session.findSessionByPubChat(3,0,function(err,docs){//查询已经被公开的会话的前10条
        if(err){
            debug("findSessionByPubChat fail", err);
        }else{
            var count = 0;
            //var length = docs.length;
            async.whilst(function () {
                return count<docs.length;
            },function(callback){
                new Message().findMessagesBysid(docs[count]._id,true,function(err,docs){
                    if (err) {
                        debug("findMessagesBysid fail", err);
                    } else {
                        //searchResult.push(doc[0].sendcontent);
                        if(count==0){
                            searchResult.push({
                                title: docs[0].sendcontent,
                                picurl: 'http://117.78.6.144/images/doctor2.jpg',
                                url: 'http://117.78.6.144/view/pubchat?sid='+docs[0].wcsessionid+'&openid='+openid
                            });
                        }else if(count==1){
                            searchResult.push({
                                title: docs[0].sendcontent,
                                picurl: 'http://117.78.6.144/images/doctor3.jpg',
                                url: 'http://117.78.6.144/view/pubchat?sid='+docs[0].wcsessionid+'&openid='+openid
                            });
                        }else if(count==2){
                            searchResult.push({
                                title: docs[0].sendcontent,
                                picurl: 'http://117.78.6.144/images/doctor1.jpg',
                                url: 'http://117.78.6.144/view/pubchat?sid='+docs[0].wcsessionid+'&openid='+openid
                            });
                        }
                        count++;
                        callback();
                    }
                });
            },function(err){
                cb(searchResult);

            });
        }

    });

    // 回复高富帅(图文回复)
    /*res.reply([
        {
            title: message.FromUserName,
            picurl: 'http://117.78.6.144/images/doctor2.jpg',
            url: 'http://117.78.6.144/images/doctor2.jpg'
        },
        {
            title: '我在家等你ee来',
            description: '',
            picurl: 'http://117.78.6.144/images/doctor3.jpg',
            url: 'http://117.78.6.144/images/logo.jpg'
        },
        {
            title: '还没来吗',
            description: '',
            picurl: 'http://117.78.6.144/images/doctor1.jpg',
            url: 'http://117.78.6.144/images/logo.jpg'
        }
    ]);*/
}

/**
 *咨询师签到，暂时将签到信息存入数据库中待以后扩展用
 */
tool.prototype.signin = function (status,isFocus, message,callback) {
    var signinDao = new SignIn();
    var sendopenid = message.FromUserName;
    var wechatutil = new wechat_util();
    //判断用户是否为咨询师
    new User().findUserByOpenid(sendopenid, function (err, user) { //根据openid查找用户信息
        if (err) {
            debug("signin fail", err);
        } else {
           // if (user.user_group == 101) {
                //判断今天是否已经签到
                var sendmsg = "系统："+user.nickname+"您好，欢迎回到奇妙在线！您会收到群友的留言，抢答并获得好评后，将获得点数奖励。";
                signinDao.findSignInByDate(sendopenid, new Date().toFormat('YYYY-MM-DD'), function (err, signin) {
                    if (signin) {//如果今天已签到则更新当前状态
                        signinDao.updateSignIn(sendopenid, new Date().toFormat('YYYY-MM-DD'),status, function(err){
                            if(err){
                                debug("updateSignIn fail", err);
                            }else{
                                //发消息给用户
                                var msg = {
                                    "sendtextmsg": sendmsg,
                                    "sendopenid": sendopenid
                                }
                                if(status=="offline"){
                                    sendmsg = "系统：期待您再次莅临！系统将暂停为您分配问题。";
                                    wechatutil.getAPI(function (api) {
                                        api.sendText(sendopenid, sendmsg, function (err, result) {
                                            if (err) {
                                                debug("send fail!", err);
                                            }else{
                                                callback(result.errmsg);
                                            }
                                        });
                                    });

                                }else if(isFocus&&signin.signState!='offline'&&status=="online"){//如果是在线状态并且点击事件还是上线提示已签到
                                    msg.sendtextmsg = "系统：今天您已经签到了。";
                                    wechatutil.getAPI(function (api) {
                                        sendMessage(api, msg, "text");
                                    });
                                }else if(isFocus){//签过到并且已下线，不是关注事件
                                    wechatutil.getAPI(function (api) {
                                        sendMessage(api, msg, "text");
                                    });
                                }


                            }
                        });


                    } else {
                        signinDao.wcopenid = sendopenid;
                        signinDao.date = new Date();
                        signinDao.signState = status;
                        signinDao.saveSignIn(signinDao, function (err) {//记录签到并增加咨询次数
                            if (err) {
                                debug("save signin fail", err);
                            } else if(isFocus){//如果是关注事件调用则不提示签到
                                //发消息给用户
                                wechatutil.getAPI(function (api) {
                                    //发消息给咨询师
                                    //var sendmsg = "系统消息：奇妙在线问诊 欢迎您回来，" + user.nickname + "!";
                                    var msg = {
                                        "sendtextmsg": sendmsg,
                                        "sendopenid": sendopenid
                                    };
                                    sendMessage(api, msg, "text");
                                    var sendmsg1 = '系统：今天已签到，咨询次数+1。';
                                    var msg1 = {
                                        "sendtextmsg": sendmsg1,
                                        "sendopenid": sendopenid
                                    };
                                    sendMessage(api, msg1, "text");
                                });
                            }
                        });
                    }
                })
           /* } else { //如果是咨询用户点击了签到
                //发消息给用户
                wechatutil.getAPI(function (api) {
                    //发消息给用户
                    var sendmsg = "系统消息：当前功能只对经过认证的专业咨询师开放!!";
                    var msg = {
                        "sendtextmsg": sendmsg,
                        "sendopenid": sendopenid
                    }
                    sendMessage(api, msg, "text");
                });
            }*/
        }
    })

}
/**
 *处理”结束会话“功能
 */
tool.prototype.closeSession = function (message) {
    var userDao = new User();
    var sessionDao = new WCSession();
    var msg = new Message();
    var fromOpneid = message.FromUserName;
    var wechatutil = new wechat_util();
    sessionDao.findSessionByOpenId({
        status: 1
    }, fromOpneid, function (err, sessions) {
        if (sessions.length > 0) {
            userDao.findUserByOpenid(fromOpneid, function (err, user) {
                if (sessions[0].receive_openid == fromOpneid) { //咨询师主动结束会话
                    //if (message.EventKey == settings.zxs_close_session_key) { //判断发送事件的用户是否为咨询师
                        sessionDao.updateSessionByReceiveOpneId(fromOpneid, function (err) {
                            if (err){
                                debug("closeSession fail", err);
                                wechatutil.getAPI(function (api) {
                                    var msg3 = {
                                        "sendtextmsg": "会话结束失败！请重试！",
                                        "sendopenid": fromOpneid
                                    }
                                    sendMessage(api, msg3, "text");
                                });
                            }else{
                                msg.countMsgBysid(sessions[0]._id,function(err,messages) {//统计双方对话次数，交互两次才扣费
                                    if (err) {
                                        debug("countMsgBysid fail", err);
                                    } else {
                                        if (messages.length>1&&messages[0].count > 1 && messages[1].count > 1) {
                                            //修改用户的咨询次数
                                            //userDao.updateUserCountByOpneId(sessions[0].send_openid, function (err) {
                                            //查询用户
                                            /*sessions.findSessionByOpenId({status:1,firstTime:1},sessions[0].send_openid,function (err, sessionlist){//查询已经建立连接且续过时的会话*/

                                                //发送消息给用户
                                                wechatutil.getAPI(function (api) {
                                                    //发消息给咨询师
                                                    var sendmsg = "系统：会话结束，感谢您的服务！";

                                                    if(sessions[0].firstTime>0){//如果续过时则提醒已扣用户点数
                                                        sendmsg = "系统：会话结束，感谢您的服务！咨询点数已经充入您的个人账户。";
                                                    }

                                                    var msg = {
                                                        "sendtextmsg": sendmsg,
                                                        "sendopenid": fromOpneid
                                                    }
                                                    sendMessage(api, msg, "text");
                                                    //发消息给咨询用户
                                                    var link = "<a href='http://117.78.6.144/publicChat?public_chat=1&sessionid=" + sessions[0]._id + "'>公开</a>";
                                                    var sendmsg2 = "系统：会话已经结束，您是否愿意公开本次对话，供其他人参考。"+link;
                                                    var msg2 = {
                                                        "sendtextmsg": sendmsg2,
                                                        "sendopenid": sessions[0].send_openid
                                                    }
                                                    sendMessage(api, msg2, "text");

                                                    var sendmsg1 = "系统：咨询师" + user.nickname + "已经结束了本次会话。请您对本次服务进行评价，回复1代表“不满意”；2代表“一般”；3代表“满意”。";
                                                    var msg1 = {
                                                        "sendtextmsg": sendmsg1,
                                                        "sendopenid": sessions[0].send_openid
                                                    }
                                                    sendMessage(api, msg1, "text");
                                                });
                                            /*});*/

                                        }else{//不扣费和咨询次数
                                            //设置此会话不扣费
                                            sessionDao.updateChargeback(sessions[0]._id,function(err){
                                                wechatutil.getAPI(function (api) {
                                                    var sendmsg2 = "系统：咨询师" + user.nickname + "已经结束了本次会话。此次对话为免费体验，将不扣除任何费用！";
                                                    var msg2 = {
                                                        "sendtextmsg": sendmsg2,
                                                        "sendopenid": sessions[0].send_openid
                                                    }
                                                    sendMessage(api, msg2, "text");


                                                    var sendmsg3 = "系统：您已经结束了本次会话，感谢您的服务。此次对话为免费体验，您暂时没有获得点数收益。";
                                                    var msg3 = {
                                                        "sendtextmsg": sendmsg3,
                                                        "sendopenid": fromOpneid
                                                    }
                                                    sendMessage(api, msg3, "text");
                                                });
                                            });

                                        }
                                    }
                                });
                            }


                        });
                   /* } else {
                        debug("ignore this request because is zxs");
                        wechatutil.getAPI(function (api) {
                            var sendmsg = "系统消息：您是咨询师，如果想结束会话请在”咨询师入口“菜单中选择”结束会话“!!";
                            var msg = {
                                "sendtextmsg": sendmsg,
                                "sendopenid": fromOpneid
                            }
                            sendMessage(api, msg, "text");
                        })
                    }*/
                } else { //用户主动结束会话
                    //if (message.EventKey == settings.zxyh_close_session_key) { //判断发送事件的用户是否为用户
                        sessionDao.updateSessionBySendOpneId2(fromOpneid, function (err) {
                            if (err){
                                debug("closeSession fail", err);
                                wechatutil.getAPI(function (api) {
                                    var message = {
                                        "sendtextmsg": "会话结束失败！请重试！",
                                        "sendopenid": fromOpneid
                                    }
                                    sendMessage(api, message, "text");
                                });
                            }else{
                            msg.countMsgBysid(sessions[0]._id,function(err,messages){//统计双方对话次数，交互两次才扣费
                                if (err) {
                                    debug("countMsgBysid fail", err);
                                }else{
                                    console.log('ssssssssssssss');
                                    if(messages.length>1&&messages[0].count>1&&messages[1].count>1){
                                        //修改用户的咨询次数
                                        //userDao.updateUserCountByOpneId(fromOpneid, function (err) {
                                        /*sessions.findSessionByOpenId({status:1,firstTime:1},sessions[0].send_openid,function (err, sessionlist){//查询已经建立连接且续过时的会话*/
                                            //发送消息给用户
                                            wechatutil.getAPI(function (api) {
                                                //发消息给自信用户
                                                var link = "<a href='http://117.78.6.144/publicChat?public_chat=1&sessionid=" + sessions[0]._id + "'>公开</a>";
                                                var sendmsg2 = "系统：会话已经结束，您是否愿意公开本次对话，供其他人参考。"+link;
                                                var msg2 = {
                                                    "sendtextmsg": sendmsg2,
                                                    "sendopenid": fromOpneid
                                                }
                                                sendMessage(api, msg2, "text");

                                                var sendmsg = "系统：请您对本次服务进行评价，回复1代表“不满意”；2代表“一般”；3代表“满意”。";
                                                var msg = {
                                                    "sendtextmsg": sendmsg,
                                                    "sendopenid": fromOpneid
                                                }
                                                sendMessage(api, msg, "text");
                                                //发消息给咨询师
                                                var sendmsg1 = "系统：用户" + user.nickname + "已经结束了本次会话，感谢您的服务！";
                                                if(sessions[0].firstTime>0){//续过时提醒
                                                    sendmsg1 = "系统：用户" + user.nickname + "已经结束了本次会话，感谢您的服务！咨询点数已经充入您的个人账户。";
                                                }
                                                var msg1 = {
                                                    "sendtextmsg": sendmsg1,
                                                    "sendopenid": sessions[0].receive_openid
                                                }
                                                sendMessage(api, msg1, "text");
                                            });
                                       /* });*/

                                    }else{//不扣费和咨询次数
                                        sessionDao.updateChargeback(sessions[0]._id,function(err){
                                            wechatutil.getAPI(function (api) {
                                                var sendmsg2 = "系统：本次对话为免费体验，将不扣除任何费用！";
                                                var msg2 = {
                                                    "sendtextmsg": sendmsg2,
                                                    "sendopenid": fromOpneid
                                                }
                                                sendMessage(api, msg2, "text");

                                                //发消息给咨询师
                                                var sendmsg1 = "系统：用户" + user.nickname + "已经结束了本次会话，感谢您的服务。此次对话为免费体验，您暂时没有获得点数收益。";
                                                var msg1 = {
                                                    "sendtextmsg": sendmsg1,
                                                    "sendopenid": sessions[0].receive_openid
                                                }
                                                sendMessage(api, msg1, "text");
                                            });
                                        });


                                    }
                                }

                            });
                            }

                        });
                   /* } else {
                        debug("ignore this request because is zxyh");
                        wechatutil.getAPI(function (api) {
                            var sendmsg = "系统消息：您是咨询用户，如果想结束会话请在”用户菜单“中选择”结束会话“!!";
                            var msg = {
                                "sendtextmsg": sendmsg,
                                "sendopenid": fromOpneid
                            }
                            sendMessage(api, msg, "text");
                        })
                    }*/
                }
            })
        } else {
            wechatutil.getAPI(function (api) {
                var sendmsg = "系统：您目前没有一对一的会话在进行中！";
                var msg = {
                    "sendtextmsg": sendmsg,
                    "sendopenid": fromOpneid
                }
                sendMessage(api, msg, "text");
            })
        }
    })
}
/**
 *
 */
tool.prototype.sendText = function (msg, callback) {
    new wechat_util().getAPI(function (api) {
        api.sendText(msg.sendopenid, msg.sendtextmsg, function (err, result) {
            if (err) debug("send message fail", err);
            callback(err, result);
        })
    })
}
/**
 *将关注用户初始化到数据库中
 *msg 事件接收的消息
 */
tool.prototype.initattentionUser = function (msg) {
    var openid = msg.FromUserName;
    var wcuser = new User();
    //发送系统消息提醒用户关注成功
    new wechat_util().getAPI(function (api) {
        var sendmsg = "系统：欢迎光临奇妙在线！点击左下角的键盘图标可以开始提问。点击“上线答疑”后，系统会为您派发其他人的问题。回答问题的质量越高，就可以赚取更多的点数。点数可以直接购买”提问“或者变现。";
        var msg = {
            "sendtextmsg": sendmsg,
            "sendopenid": openid
        }
        sendMessage(api, msg, "text");
    });

    //关注成功后，用户信息插入本地数据库。
    wcuser.findUserByOpenid(openid, function (err, user) {
        if (user) {
            new tool().signin('online',false,msg);//关注事件系统自动给用户签到
            //更新用户
            new wechat_util().getAPI(function (api) {
               // api.moveUserToGroup(openid, 101, function(err, gpresult) {//移动微信平台用户所属的组为咨询师组20150306
                api.getWhichGroup(openid, function (err, gpresult) {
                    if (gpresult) {
                        wcuser.user_group = gpresult.groupid;
                        //wcuser.user_group = 101;20150306
                        api.getUser(openid, function (err, uresult) {
                            if (uresult) {
                                //wcuser.nickname = uresult.nickname;
                                //wcuser.createtime = new Date();
                                var headimgurl = uresult.headimgurl;
                                debug("this nickname is ", uresult.nickname);
                                var options = {
                                    user_group: gpresult.groupid,//20150306
                                    //user_group: 101,//20150306
                                    nickname: uresult.nickname,
                                    headimgurl : headimgurl.slice(0,headimgurl.lastIndexOf("/0"))+"/64",//用户头像str.slice(0,str.lastIndexOf('/0'));
                                    createtime : new Date()
                                };
                                wcuser.updateUserByOpneId(openid, options, function (err) {
                                    if (err) {
                                        debug("update user fail", err);
                                    }
                                })
                            } else {
                                debug("initattentionUser find no user");
                            }

                        })
                    } else {
                        debug("initattentionUser find no group");
                    }
                });
            });
        } else {
            //插入用户
            new wechat_util().getAPI(function (api) {
                wcuser.wcopenid = openid;
                wcuser.weight = 0;
                wcuser.count = 10;
                wcuser.random = Math.random();
                //wcuser.user_group = 101;20150306
                //api.moveUserToGroup(openid, 101, function(err, gpresult) {//移动微信平台用户所属的组为咨询师组20150306
               // });
                api.getWhichGroup(openid, function (err, gpresult) {
                    if (gpresult) {
                        wcuser.user_group = gpresult.groupid;//20150306
                        api.getUser(openid, function (err, uresult) {
                            if (uresult) {
                                wcuser.nickname = uresult.nickname;
                                wcuser.createtime = new Date();
                                debug("this nickname is ", uresult.nickname);
                                wcuser.saveUser(function (err) {
                                    if (err) {
                                        debug("insert user fail", err);
                                    }else{
                                        new tool().signin('online',false,msg);//关注事件系统自动给用户签到
                                    }
                                })
                            } else {
                                debug("initattentionUser find no user");
                            }
                        })
                    } else {
                        debug("initattentionUser find no group");
                    }
                });
            })
        }
    });
}
/**
 *用户咨询，咨询消息会根据权重发给前5名处于空闲状态的咨询师
 *用户发起咨询，消息内容必须是文字或微信表情
 *user 发起咨询的用户对象
 *message 用户发送的消息
 *callback 回调函数 (err,result)
 */
function userAsk(user, message, callback) {
    //获取发送者的openid和昵称
    var fromOpneid = user.wcopenid;
    var nickname = user.nickname;
    var wechatutil = new wechat_util();
    var sessionDao = new WCSession();
    //判断之前用户是否发起过提问且未被咨询师回答的（status=0）
    sessionDao.findSessionBySendOpenId(fromOpneid, function (err, sessions) {
        if (sessions.length > 0) {
            //将会话的status更新为2
            sessionDao.updateSessionBySendOpneId2(fromOpneid, function (err) {
                if (err) debug("userAsk updateSessionBySendOpneId2 is fail", err);
            })
        }
        //获取api
        if (user.count <= 0) { //如果用户的咨询次数已经用完
            wechatutil.getAPI(function (api) {
                var linkmsg = "<a href='http://117.78.6.144/wcpay/goodslist'>购买提问</a>";
                var sendmsg = "系统：您可提问的次数已经用完。点击”其他操作“中的"+linkmsg+"进行追加。";
                var msg = {
                    "sendtextmsg": sendmsg,
                    "sendopenid": fromOpneid
                }
                sendMessage(api, msg, "text");
            })
        } else {
            var userDao = new User();
            //创建会话
            sessionDao.send_openid = fromOpneid;
            sessionDao.status = 0; //会话发起
            sessionDao.start_date = new Date();
            sessionDao.saveWCSession(function (err) {
                if (err) {
                    debug("save session error!", err);
                    callback(err);
                } else {
                    //查询能够分配的咨询师人数

                    //发送消息通知用户等待
                   /* wechatutil.getAPI(function (api) {
                        var pubchatlink = "\n<a href='http://117.78.6.144/view/pubchat?uuid="+user._id+"'>点此链接可在公开对话中搜索关注的话题</a>";
                        var sendmsg = " 正在为您分配咨询师，目前已经有" + settings.receiver + "位咨询师收到了您的问题，请等待..."+pubchatlink;
                        var msg = {
                            "sendtextmsg": sendmsg,
                            "sendopenid": fromOpneid
                        }
                        sendMessage(api, msg, "text");*/
                        //发给5个咨询师
                        userDao.findTopUser(fromOpneid, function (err, result, userCount) {
                            if (err) {
                                callback(err);
                            } else {
                                wechatutil.getAPI(function (api) {
                                    var pubchatlink = "<a href='http://117.78.6.144/view/pubchat?uuid=" + user._id + "'>搜索</a>";
                                    var sendmsg = " 系统：正在为您分配咨询师，目前问题已经发给了" + userCount + "位咨询师，请等待应答...等待时可查看热门话题。"//点击下面链接搜索相似问题：" + pubchatlink;
                                    //20150306var sendmsg = " 系统：请等待应答... 可点击下面链接搜索相似话题：" + pubchatlink;

                                    if(userCount==0){
                                        sendmsg = "系统：目前没有空闲的咨询师。";
                                    }
                                    var msg = {
                                        "sendtextmsg": sendmsg,
                                        "sendopenid": fromOpneid
                                    }
                                    sendMessage(api, msg, "text");

                                    if (result.length > 0) {
                                        debug('this ask userlist is', result);
                                        var count = 0;
                                        async.whilst(
                                            function () {
                                                return count < result.length;
                                            },
                                            function (wcb) {
                                                var link = "<a href='http://117.78.6.144/grab?sendopenid=" + fromOpneid + "&receiveopenid=" + result[count] + "'>我来回应</a>";
                                                if (message.MsgType == "text") {
                                                    var sendmsg = nickname + "说：" + message.Content + "  " + link;
                                                    var msg = {
                                                        "sendtextmsg": sendmsg,
                                                        "sendopenid": result[count]
                                                    };
                                                    sendMessage(api, msg, "text");
                                                } else {
                                                    var msg = {
                                                        "nickname": nickname,
                                                        "message": message,
                                                        "linkmsg": link,
                                                        "sendopenid": result[count]
                                                    };
                                                    sendMessage(api, msg, message.MsgType);
                                                }
                                                count++;
                                                wcb();
//                                            setTimeout(wcb, settings.sendmsginterval);
                                            },
                                            function (err) {
                                                debug('Ask send user end!');
                                            }
                                        )
                                    }
                                });


//                                _.each(result, function (wcopenid, index, list) {
//
//                                    var link = "<a href='http://117.78.6.144/grab?sendopenid=" + fromOpneid + "&receiveopenid=" + wcopenid + "'>我来回答</a>";
//                                    if (message.MsgType == "text") {
//                                        var sendmsg = nickname + "说：" + message.Content + "  " + link;
//                                        var msg = {
//                                            "sendtextmsg": sendmsg,
//                                            "sendopenid": wcopenid
//                                        }
//                                        sendMessage(api, msg, "text");
//                                    } else {
//                                        var msg = {
//                                            "nickname": nickname,
//                                            "message": message,
//                                            "linkmsg": link,
//                                            "sendopenid": wcopenid
//                                        }
//                                        sendMessage(api, msg, message.MsgType);
//                                    }
//                                })
                            }
                        });
                   /* })*/
                    // //消息存储
                   new tool().saveMsg(message, function (err) {
                        debug("add new Message", err);
                    })
                }
            })
        }
    })
}

/**
 *发送消息(包含文本、图片、语音和视频)
 *msg（在微信消息的基础上封装的对象）：
 *    var msg = {
 *		"nickname": nickname,
 *		"message": message,
 *		"sendopenid": fromOpneid
 *	}
 *msgtype 微信平台的消息类型
 */
function sendMessage(api, msg, msgtype) {
    var msg = msg;
    var msgtype = msgtype;
    if (msgtype == "text") {
        var sendtextmsg;
        if (msg.sendtextmsg) { //直接将发送的内容传过来
            sendtextmsg = msg.sendtextmsg;
        } else {
            sendtextmsg = msg.nickname + "说:" + msg.message.Content;
        }
        api.sendText(msg.sendopenid, sendtextmsg, function (err, result) {
            if (err) {
                debug("send fail!", err);
                if (result) {
                    if (result.errcode != 45015) { //如过选择的咨询师已经过长时间没有和公众账号互动
                        var refresh = true;
                        new wechat_util().getAPI(function (api) {
                            sendMessage(api, msg, msgtype);
                        }, refresh);
                    }
                }
            }
        });
    } else if (msgtype == "image") {
        var sendtextmsg;
        if (msg.linkmsg) {
            sendtextmsg = msg.nickname + "发来照片:" + msg.linkmsg;
        } else {
            sendtextmsg = msg.nickname + "发来照片:";
        }
        api.sendText(msg.sendopenid, sendtextmsg, function (err, result) {
            if (err) {
                debug("send fail!", err);
                if (result) {
                    if (result.errcode != 45015) { //如过选择的咨询师已经过长时间没有和公众账号互动
                        var refresh = true;
                        new wechat_util().getAPI(function (api) {
                            sendMessage(api, msg, msgtype);
                        }, refresh);
                    }
                }
            } else {
                api.sendImage(msg.sendopenid, msg.message.MediaId, function (err, result) {
                    if (err) debug("send fail!", err);
                })
            }
        });
    } else if (msgtype == "voice") {
        var sendtextmsg;
        if (msg.linkmsg) {
            sendtextmsg = msg.nickname + "传来语音:" + msg.linkmsg;
        } else {
            sendtextmsg = msg.nickname + "传来语音:";
        }
        api.sendText(msg.sendopenid, sendtextmsg, function (err, result) {
            if (err) {
                debug("send fail!", err);
                if (result) {
                    if (result.errcode != 45015) { //如过选择的咨询师已经过长时间没有和公众账号互动
                        var refresh = true;
                        new wechat_util().getAPI(function (api) {
                            sendMessage(api, msg, msgtype);
                        }, refresh);
                    }
                }
            } else {
                api.sendVoice(msg.sendopenid, msg.message.MediaId, function (err, result) {
                    if (err) debug("send fail!", err);
                })
            }

        });
    } else if (msgtype == "video") {
        var sendtextmsg = msg.nickname + "送上视频:";
        api.sendText(msg.sendopenid, sendtextmsg, function (err, result) {
            if (err) {
                debug("send fail!", err);
                if (result.errcode != 45015) { //如过选择的咨询师已经过长时间没有和公众账号互动
                    var refresh = true;
                    new wechat_util().getAPI(function (api) {
                        sendMessage(api, msg, msgtype);
                    }, refresh);
                }
            } else {
                api.sendVideo(msg.sendopenid, msg.message.MediaId, msg.message.ThumbMediaId, function (err, result) {
                    if (err) debug("send fail!", err);
                })
            }

        })
    } else if (msgtype == "music") {
        // {
        //  "touser":"OPENID",
        //  "msgtype":"music",
        //  "music": {
        //    "title":"MUSIC_TITLE", // 可选
        //    "description":"MUSIC_DESCRIPTION", // 可选
        //    "musicurl":"MUSIC_URL",
        //    "hqmusicurl":"HQ_MUSIC_URL",
        //    "thumb_media_id":"THUMB_MEDIA_ID"
        //  }
        // }
        api.sendMusic(msg.sendopenid, msg.music, function (err, result) {
            if (err) debug("send success!", err);
        })

    } else if (msgtype == "news") {
        // {
        //  "touser":"OPENID",
        //  "msgtype":"news",
        //  "news":{
        //    "articles": [
        //      {
        //        "title":"Happy Day",
        //        "description":"Is Really A Happy Day",
        //        "url":"URL",
        //        "picurl":"PIC_URL"
        //      },
        //      {
        //        "title":"Happy Day",
        //        "description":"Is Really A Happy Day",
        //        "url":"URL",
        //        "picurl":"PIC_URL"
        //      }]
        //   }
        // }
        api.sendNews(msg.sendopenid, msg.news, function (err, result) {
            if (err) debug("send success!", err);
        })
    }
}

/**
 * 获取图片并编码
 * @param message
 */
function getImage(message){

}

/**
 *
 * @param openid
 * @param callback
 */
tool.prototype.getpayoffinfo = function(openid,callback){

        var message = new Message();
        var pubChatPay = new PubChatPay();
        async.waterfall([
            function (cb) {
                //查询结账单中该用户最后一次结账的时间
                new PayOff().findPayoff({wcopenid: openid}, function (err, result) {
                    if (err) {
                        debug('findPayoff fail', err);
                        cb(err, '');
                    } else {
                        if (result.length > 0) {//如果查询该用户结账单不为空,拿到
                            var payoff_date = result[0].payoff_date;
                            var total_count = 0;
                            _.each(result, function (payoff, index, list) {
                                total_count += payoff.payoff_count;
                            })
                            cb(null, payoff_date, total_count);
                        } else {
                            cb(null, null, null);
                        }
                    }
                });
            },
            function (payoff_date, total_count, cb) {
                //查询本次结算单的session数量（续时的session根据续时次数增加本次结算次数）
                var condition = {
                    stat: {$lt: 2},//0代表评价未统计;1代表评价已统计;2代表结算已统计
                    receive_openid: openid,
                    status: 2,
                    chargeback:0,
                    build_date: {
                        $gte: payoff_date
                    }
                };
                if (!payoff_date) {
                    delete condition['build_date'];
                }

                var condition1 = {
                    "$or":[{"send_openid":openid},{"receive_openid":openid}],
                    date: {
                        $gte: payoff_date
                    }
                };
                new WCSession().findSessionCommon(condition, function (err, result) {//统计正常会话的次数
                    pubChatPay.findPubChatPayById(condition1, function(err,docs){
                        var payoff_count = 0;
                        var payoff_info = new PayOff();
                        _.each(result, function (session, index, list) {
                            if (session.relet_count) {//获取用户续费次数默认0为1次
                                var rcount = session.relet_count + 1;
                                payoff_count += rcount;
                            } else {
                                payoff_count++;
                            }
                        });

                        _.each(docs, function (pubChatPay, index, list){
                            if(openid==pubChatPay.send_openid){//如果此openid等于咨询者id则统计为咨询者分成
                                payoff_count += pubChatPay.allocation;
                            }else{//统计为咨询师分成
                                payoff_count += pubChatPay.receiveAllocation;
                            }

                        });

                        payoff_info.payoff_count = parseFloat(payoff_count).toFixed(3);//所有会话总的结算次数
                        //payoff_info.income = payoff_count * settings.perincome;
                        payoff_info.income = parseFloat(payoff_count*settings.perincome).toFixed(3);
                        payoff_info.payoff_totalcount = parseFloat(payoff_count + total_count).toFixed(3);
                        cb(err, payoff_info);
                    });

                });
            }
        ], function (err, result) {
            callback(err, result);
        });

}

module.exports = tool;